<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import { onMounted, watch } from 'vue';

import { useFs, useUi } from '@fast-crud/fast-crud';
import consola from 'consola';
import { forEach } from 'lodash-es';

import { createCrudOptions } from '../data/meta-crud';

defineOptions({
  name: '资源元数据',
  inheritAttrs: false,
});

const props = withDefaults(defineProps<Props>(), {
  modelValue: '{}',
  mode: 'view',
});
const emit = defineEmits<Emits>();
interface Props {
  modelValue?: string;
  mode?: string;
}
interface Emits {
  (e: 'update:modelValue', value: string): void;
}

const { crudRef, crudBinding } = useFs({
  createCrudOptions,
  context: { emit, mode: props.mode },
});
const { ui } = useUi();
const formItemContext = ui.formItem.injectFormItemContext();

function handleEmit(data: any) {
  emit('update:modelValue', data);
  formItemContext.onBlur();
  formItemContext.onChange();
}

// 页面打开后获取列表数据
onMounted(async () => {
  watch(
    () => {
      return props.modelValue;
    },
    (value: string) => {
      let obj = {};
      try {
        obj = JSON.parse(value || '{}');
      } catch (error) {
        consola.log('error', error);
        obj = [];
      }

      const list: Recordable[] = [];
      forEach(obj, (v, key) => {
        list.push({ key, value: v });
      });
      crudBinding.value.data = list;

      handleEmit(JSON.stringify(obj));
    },
    {
      immediate: true,
    },
  );
});
</script>

<template>
  <div class="meta-input">
    <FsCrud ref="crudRef" v-bind="crudBinding" />
  </div>
</template>
<style lang="scss" scoped>
.fs-crud-container {
  .fs-crud-footer {
    display: none;
  }
}
</style>
